var xmlHttp;    //用于保存XMLHttpRequest对象的全局变量
//用于创建XMLHttpRequest对象
function createXmlHttp() {
    //根据window.XMLHttpRequest对象是否存在使用不同的创建方式
	 try
	    {
	   // Firefox, Opera 8.0+, Safari
	    xmlHttp=new XMLHttpRequest();
	    }
	 catch (e)
	    {

	  // Internet Explorer
	   try
	      {
	      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	      }
	   catch (e)
	      {

	      try
	         {
	         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
	         }
	      catch (e)
	         {
	         alert("您的浏览器不支持AJAX！");
	         return false;
	         }
	      }
	    }
}

function refreshCart() {
    sendRequest("");
}

function addProduct(pid) {
	var P_buynum=document.form_test.buynum.value;
	  var buynum=P_buynum.Trim();
	  var allnum=document.form_test.allnum.value;
	  var reg = /^[1-9]\d{0,}/;
	if(!buynum.match(reg)){
     window.alert("请输入正确的数字");
	 document.form_test.buynum.focus();
	 return false;
	}
  
   else if(parseInt(buynum)>parseInt(allnum)){
     window.alert("购买量不能大于库存量！");
	 document.form_test.buynum.focus();
	 return false;
	 
   }
   else if(buynum.match(reg)&&parseInt(buynum)<=parseInt(allnum)){
	var r = confirm("确定添加该商品到购物车？");
    if(r)
    	{
    		sendRequest("&action=add&pid=" + pid +"&buynum=" +document.all['buynum'].value);
    	}else
    	{
    		return false;
    	}
    }
	else {
     window.alert("输入有误");
	 document.form_test.buynum.focus();
	 return false;
	 
   }
}
String.prototype.Trim = function() 
   { 
    return this.replace(/\s/g,""); 
   }
function addProductFromProductItem(pid) {
	
	  
	var r = confirm("确定添加该商品到购物车？");
    if(r)
    	{
    		sendRequest("&action=add&pid=" + pid +"&buynum=1");
    	}else
    	{
    		return false;
    	}
    
}

function emptyCart() {
	var r = confirm("确定清空购物车？");
	if(r)
		{
			sendRequest("&action=empty");
		}else{
			return false;
		}
}

function delProduct(pid) {
	var r = confirm("确定从购物车中删除该商品？");
	if(r)
	{
		sendRequest("&action=del&pid=" + pid);
	}else{
		return false;
	}
}

function sendRequest(params) {
    createXmlHttp();                       
    xmlHttp.open("POST", "pages/cart/cart.jsp?timestamp=" + new Date().getTime() + params, true);
    xmlHttp.onreadystatechange = showCartInfo;
    xmlHttp.send(null);
}


function showCartInfo() {
    if (xmlHttp.readyState == 4) {
        document.getElementById("shoppingcart").innerHTML = xmlHttp.responseText;
    }
}
